package util

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
//	"golang.org/x/text/encoding/simplifiedchinese"
  //  "golang.org/x/text/transform"
    "bytes"
    "regexp"
     "time"
   // "strconv"

)

var __baidu = &Baidu{}


type Baidu struct {
	expires_in int 
	token string
	lasttime  int64
}

 
type Session struct {
	AccessToken   string `json:"access_token"`
	RefreshToken  string `json:"refresh_token"`
	SessionKey    string `json:"session_key"`
	SessionSecret string `json:"session_secret"`
	Scope         string `json:"scope"`
	ExpiresIn     int    `json:"expires_in"`
}

type Words struct {
	Words string `json:"words"`
}



type Result struct {
	LogId     int64       `json:"log_id"`
	Direction int         `json:"direction"`
	Wrn       int         `json:"words_result_num"`
	Wr        []Words    `json:"words_result"`
	words     string      `json:"words"`
}


func (words *Words) String() string {
    b, err := json.Marshal(*words)
    if err != nil {
        return fmt.Sprintf("%+v", *words)
    }
    var out bytes.Buffer
    err = json.Indent(&out, b, "", "    ")
    if err != nil {
        return fmt.Sprintf("%+v", *words)
    }
    return out.String()
}

 
const (
	clientID     = "fb25yK4nt3xGmHloyrZGyop5"          // API Key
	clientSecret = "YXtxZ3o8VdlVsC5XnPI1T7OcmHkRR5wf"  // Secret Key
)


func BaiduOCR(img []byte) (result string, err error) {
	
	if __baidu.expires_in == 0 || time.Now().Unix() > __baidu.lasttime {
		err := accessToken(clientID, clientSecret)
		if err != nil {
			fmt.Println("accessToken()", err)
			return "",err
		}
	}
	
	conts ,err := imageToText(__baidu.token, img)
	if err != nil {
		fmt.Println("ImageToText()", err)
		return "",err
	}
	
	all := ""
	for i := range conts.Wr {
       // fmt.Println(conts.Wr[i].Words)
         all = all +conts.Wr[i].Words
    }
	
	return all, nil
}

func GetIngredient(str *string)(l []string){
	reg := regexp.MustCompile("明矾|鲸蜡醇|硫酸镁|苯甲酸钠|乙二醇二硬脂酸酯|苯甲醇|聚二甲基硅氧烷|甲醇")
	return reg.FindAllString(*str, -1)
}

/*
func main() {

	img, err := ioutil.ReadFile("C:/Users/spark/Pictures/QQ20181127224703.png")
	if err != nil {
		fmt.Println("ioutil.ReadFile()", err)
		return
	}

	str, err := BaiduOCR(img)
	
	if err != nil {
		fmt.Println("baiduOCR", err)
		return
	}

	  fmt.Println(str)
	
	reg := regexp.MustCompile("明矾|鲸蜡醇|硫酸镁|苯甲酸钠|乙二醇二硬脂酸酯|苯甲醇|聚二甲基硅氧烷|甲醇")
	fmt.Printf("%v\n", reg.FindAllString(str, -1))
	//fmt.Println("Result: ", vl.Wr)

}
*/

func accessToken(id string, secret string) (err error) {
	apiURL := fmt.Sprintf("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s", id, secret)
	resp, err := http.Get(apiURL)
	if err != nil {
		return  err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	var session Session
	err = json.Unmarshal(body, &session)
	if err != nil {
		return  err
	}
	//fmt.Println("Token:", session)
	
	// fmt.Printf("v1 type:%T\n", time.Now().Unix())
 
	//cc,err := strconv.Atoi(session.ExpiresIn)  
	__baidu.token = session.AccessToken
	__baidu.expires_in = session.ExpiresIn
	__baidu.lasttime = time.Now().Unix() + int64(__baidu.expires_in - 86400)
	//str_time := time.Unix(endtime, 0).Format("2006-01-02 15:04:05")
	//fmt.Println(str_time)
	//fmt.Println("time:", time.Now().Unix())  
	fmt.Println("Token:", __baidu.token)
	fmt.Println("lasttime:", __baidu.lasttime)
	return nil
}



func imageToText(token string, image []byte)(result Result, err error) {
	apiURL := fmt.Sprintf("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=%s", token)
	param := "image=" + url.QueryEscape(base64.StdEncoding.EncodeToString(image))
	resp, err := http.Post(apiURL, "application/x-www-form-urlencoded", strings.NewReader(param))
	if err != nil {
		return result,err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return result,err
	}
	//fmt.Println("body: ", string(body))
	var rt Result
	//fmt.Println("body: ", body)
	err = json.Unmarshal(body, &rt)
	if err != nil {
		return result,err
	}

	//fmt.Println(rt.Wr);

	return rt,nil
}

 

